<template>
	<view v-if="is_show_info">
		<!-- 重复观看视频弹框  time 倒计时时间-->
		<!-- <newAnswerRepeat :info="{username:'王卫东',video_title:'视频答题标题',end_time:'2020-12-12 00',shop_name:'店长名称'}" time="2000"></newAnswerRepeat> -->
		<!-- 视频 -->
		<video
			id="myVideo" 
			autoplay
			:poster="videoInfo.coverUrl"
			:src="videoInfo.videoAddress"
			@timeupdate="videoTimeUpdateEvent"
			@ended="videoEnd"
			@play="videoPlay"
			style="width: 100%;"
			:show-fullscreen-btn="false"
			:enable-progress-gesture="false"
			:http-cache="true"
			>	
		</video>
		<view class="b-box">
			 <!-- 视频标题 -->
			<view class="video-name">{{ videoInfo.titleCus }}</view>
			<view class="video-date">
				<view class="video-date-end-date">答题截止时间：</view>
				<view class="video-date-value">{{ videoInfo.endTime }}</view>
			</view>
			<view class="video-desc">
				<view class="video-desc-item">
					<view class="icon"><uni-icons type="info" color="#666"></uni-icons></view>
					<view class="msg">播放完成后才能开始答题</view>
				</view>
				<view class="video-desc-item">
					<view class="icon"><uni-icons type="info" color="#666"></uni-icons></view>
					<view class="msg">答题完成后，点击底部“提交”按钮完成答题</view>
				</view>
			</view>
			<view class="answer" v-for="item in  videoInfo.questionList">
				<view class="answer-title">{{ item.question }}</view>
				<view class="answer-choose" v-for="itemTwo in item.answers">
					<view class="answer-choose-left">{{ itemTwo }}</view> 
				</view>
			</view>
			<!-- <view class="answer-btn">确定</view> -->
			<view style="height: 50upx;"></view>
		</view>
		<!-- 遮罩层 -->
		<view v-if="reward !== null" class="mask">
			<View class="task-enter-container">
				<image mode="widthFix" :src="`${imgBasePath}newtask/task-people-task-enter-bg.png`" class="task-enter-bg"></image>
				<View class="task-enter-view">
					<View class="reward">
					<Text class="number">{{reward}}</Text>
					<Text class="unit">元</Text>
					</View>
					<View class="button" @click="goToNewPeopleTask()"></View>
				</View>
				<View class="close-view" @click="this.reward = null">
					<image class="close-icon" mode="widthFix" :src="`${imgBasePath}newtask/close.png`"></image>
				</View>
			</View>
		</view>
	</view>
</template>

<script>
import { COS } from 'cos-wx-sdk-v5';
import { imgBasePath } from "@/common/config";
	export default {
		data() {
			return {
				is_look:true, // 是否链接失效 判断code存不存在
				requestCode:'', // 服务器端code
				videoId:0, // 视频id
				videoInfo:{}, // 视频答题界面信息
				oldPlayTime:0,
				g_z_code:"",//公众号code
				
				is_show_info:true,
				activityId:'', // 活动id
				
				ids:[],
				reward: null,
				imgBasePath,
			}
		},
		onLoad(req) {
			if(req.g_z_code){
				this.g_z_code=req.g_z_code
			}
			if(req.requestCode) {
				this.requestCode = req.requestCode;
			}else {
				this.is_look = false;
			}
			this.videoId = req.videoId;
			this.$dadian("");
			// this.getVideoInfo();
		},
		onShow() {
			this.videoContext = uni.createVideoContext('myVideo');
			
			var that = this;
			setTimeout(function() {
				//#ifdef H5
				that.g_z_login()
				//#endif
				//#ifdef MP-WEIXIN
				that.login();
				// #endif
				
			},300)
			this.setLookSotageTime();
		},
		methods: {
			// 获取入口权限
			getTaskEnterLimits() {
				return this.$request("marketing/user/activity/available", {params: {source: "Popup", activityType: "New_People_Task"}})
				.then(data => data.result).catch(() => null);
			},
			// 去新人任务页面
			goToNewPeopleTask() {
				uni.redirectTo({
					url: '/pages/newPeopleTask/index'
				});
			},
			// 获取活动详情
			getActivityDetail() {
				return this.$request("marketing/user/activity", { method: "GET", params: { activityType: "New_People_Task" } })
					.then(data => data)
					.catch(() => null);
			},
			// 登录 检测是否答题等信息
			login() {
				var that = this;
				uni.login({
					provider: 'weixin',
					success: function (loginRes) {
						that.loginTwo(loginRes.code);
					},
				})
			},
			//公众号登陆
			g_z_login()
			{
				if(this.g_z_code){
					this.loginTwo(this.g_z_code)
				}else{
					uni.setStorageSync("gzh_url",window.location.href)
					uni.reLaunch({
						url:"/pages/login/gzh_login"
					})
				}
			},
			loginTwo(code) {
				var that = this;
				var data = {
					code:code,
					requestCode:this.requestCode  
				};
				//#ifdef H5
				data.isH5=1;
				//#endif
				this.$NoteApi.doRequest("get", "login", data).then(async res => {
					// 跨店
					if(res.data.code == 408) {
						this.is_show_info = false;
						uni.showModal({
							title:'提示',
							content:res.data.message,
							showCancel:false,
							success() {
								uni.switchTab({
								    url:'/pages/sindex/index'
								})
							}
						})
						return
					}
					// 活动结束
					if(res.data.code == 409) {
						uni.reLaunch({
							url:'/pages/newAnswer/endTwo?code='+this.requestCode+'&video_id='+this.videoId
						})
						return
					}
					if(res.data.code == 0){
						this.activityId = res.data.data.activityId;
						var invitorInfo = res.data.data.invitorInfo;
						uni.setStorageSync("token", res.data.data.token)
						uni.setStorageSync("userInfo", res.data.data);

						try {
							const hasTaskEnterLimits = await this.getTaskEnterLimits();
							if (hasTaskEnterLimits) {
								const activityDetail = await this.getActivityDetail();
								this.reward = activityDetail.reward / 100;
								return;
							}
						} catch(error) {}

						// 1 新用户 去注册 0 老用户
						if(res.data.data.isNew == 1) {
							//#ifdef H5
							uni.showModal({
								content:'您还未注册成为本店会员，请到人康课堂小程完成注册后访问该链接',
								title:"提示"
							})
							return false;
							//#endif
							uni.navigateTo({
								url:'/pages/newAnswer/register?sheng='+invitorInfo.deptProvince+'&shi='+invitorInfo.deptCity+'&deptName='+invitorInfo.deptName+'&invitorCode='+invitorInfo.invitorCode+'&requestCode='+this.requestCode
							})
						}else {
							// 判断是否重复答题
							if(res.data.data.hasDone == 1) {
								uni.reLaunch({
									url:'/pages/newAnswer/endThree?code='+this.requestCode+'&video_id='+this.videoId+'&activityId='+this.activityId
								})
							}else {
								that.getIds();
								// that.getVideoInfo();
							}
							
						}
					}else {
						if(data.isH5==1 && data.code){
							var url=window.location.origin+window.location.pathname+'#/pages/newAnswer/index?requestCode='+data.requestCode+'&videoId='+this.videoId
							window.location.href=url
						}
						uni.showToast({
							title:res.data.message,
							icon:'none'
						})
					}
				})
			},
			//  第一次，不存在 / ==[]，直接[] 调用，成功后调用添加
			//  第二次，
			// 有就放 没就直接请求 ids==[]
			getIds() {
			    var that = this;
				var answer_info = uni.getStorageSync('user_answers');
				for(var i = 0; i < answer_info.length;i++) {
				    if(that.videoId == answer_info[i].videoId) {
				        that.ids = answer_info[i].answers
				    }
				}
				that.getVideoInfo();
			},
			// 获取视频信息详情
			getVideoInfo() {
				var that = this;
				var data = {
					videoId:Number(this.videoId),
					questionIds:that.ids,
				};
				that.$NoteApi.doRequest("post", "ruiVideo/detail", data,'json').then(res => {
					if(res.data.code == 0){
						this.videoInfo = res.data.data;
						if(this.ids.length == 0) {
							that.set_Storage();
						}
					}
				})
			},
			// 如果第一次看当前视频 设置缓存 答对后删除
			set_Storage() {
				var that = this,setIds = [];
				for(var i = 0; i < that.videoInfo.questionList.length; i++ ) {
				    setIds.push(that.videoInfo.questionList[i].id)
				}
				var get_arr = uni.getStorageSync('user_answers');
				if(!get_arr) get_arr = []
				get_arr.push({
				    videoId:that.videoId,
				    answers:setIds
				})
				this.ids = setIds;
				uni.setStorage({ key: 'user_answers',data: get_arr });
			},
			
			// 检测是否有当前视频的缓存时间节点
			setLookSotageTime() {
				// 获取 - 缓存是否存在当前视频的时长
				var that = this;
				var time_num = uni.getStorageSync(that.videoId);
				// 如果存在 设置上次时间
				if(time_num){
					setTimeout(function() {
						that.videoContext.seek(Number(time_num))
						that.oldPlayTime = time_num;
					},1000)
				}
			},
			// 监听视频不可快进
			videoTimeUpdateEvent(e) {
				// console.log(e.detail.currentTime)
				var that = this;
				let currentTime = Number(e.detail.currentTime);
				console.log(e);
				// 如果快进 设置为oldTIme
				if((currentTime - this.oldPlayTime) > 5) {
					this.videoContext.seek(this.oldPlayTime)
				}else {
					if(currentTime != 0) {
						// 如果存在上一次的节点 设置为上一次未看完的时间节点
						if(currentTime < 1 && this.oldPlayTime > 1) {
							this.videoContext.seek(this.oldPlayTime)
						}else {
							this.oldPlayTime = currentTime;
							// 存储当前视频播放进度
							uni.setStorage({ key: this.videoId,data: currentTime });
						}
					}else {
						// this.videoContext.seek(currentTime) 
					}
				}
			},
			// 视频结束的时候触发
			videoEnd() {
				var that = this;
				this.actionReport(4);
				uni.removeStorageSync(this.videoId);
				uni.navigateTo({
					url:'/pages/newAnswer/answer?code='+this.requestCode+"&videoId="+this.videoId+'&activityId='+this.activityId+'&ids='+encodeURIComponent(this.ids)
				})
			},
			// 视频开始的时候触发
			videoPlay() {
				this.actionReport(3);
			},
			// 行为上报
			actionReport(type) {
				var that = this;
				if(type == 3) {
					var data = {
						videoId:this.videoId,
						action:3,
						entrance:100,
					}
				}else {
					var data = {
						videoId:this.videoId,
						action:4,
						duration:this.oldPlayTime,
						entrance:100,
						fromChicken:0,
					};
				}
				that.$NoteApi.doRequest("post", "action/report", data,'json').then(res => {
					if(res.data.code == 0){
						
					}
				})
			},
		},
	}
</script>

<style lang="scss" scoped>

.mask {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 1;
  display: flex;
  align-items: center;
  background: rgba(0,0,0,0.50);
}
.task-enter-container {
  position: absolute;
  z-index: 3;
  display: flex;
  flex-direction: column;
  align-items: center;
  .task-enter-bg {
    width: 100vw;
  }
  .task-enter-view {
    position: absolute;
    text-align: center;
    top: 0;
    width: 100%;
    .reward {
      margin-top: 150rpx;
      color: #FD3236;

      .number {
        font-size: 120rpx;
        font-family: "Futura-Bold";
        font-weight: 700;
      }
      .unit {
        font-family: "PingFangSC-Medium";
        font-size: 60rpx;
        font-weight: 500;
        margin-left: 10rpx;
      }
    }
    .button {
      display: inline-block;
      margin-top: 135rpx;
      width: 380rpx;
      height: 110rpx;
    }
  }
  .close-view {
	padding: 20rpx;
	width: 129rpx;
	height: 129rpx;
	margin-top: 35rpx;
	.close-icon {
		width: 109rpx;
	}
  }
}
.b-box {
	width: 690upx;
	min-height: 10upx;
	margin: 0 auto;
}
.video-name {
	width: 690upx;
	font-size: 36upx;
	font-weight: 500;
	color: #000;
	overflow:hidden;
	text-overflow:ellipsis;
	display:-webkit-box;
	-webkit-line-clamp:2;
	-webkit-box-orient:vertical;
	min-height: 10upx;
	margin-top: 30upx;
	margin-bottom: 20upx;
}
.video-tag {
	display: inline-block;
	min-width: 10upx;
	height: 54upx;
	line-height: 54upx;
	background: #EA7C0F;
	color: #fff;
	padding: 0 20upx;
	border-radius: 28upx 0upx 28upx 0upx;
}
.video-info {
	min-height: 10upx;
	margin: 30upx 0;
	color: #666;
	font-size: 28upx;
	display: flex;
}
.video-info-time {
	flex: 1;
}
.video-info-num {
	
}
.video-answer-num {
	color: #666;
	font-size: 28upx;
	margin: 30upx 0;
}

.answer {
	min-height: 10upx;
	margin-bottom: 40upx;
}
.answer-title {
	line-height: 48upx;
	color: #333;
	font-weight: 600;
	font-size: 32upx;
	margin-bottom: 30upx;
}
.answer-choose {
	min-height: 10upx;
	background-color: #fff;
	background: #F0F0F0;
	border-radius: 16upx;
	font-size: 36upx;
	color: #333;
	font-weight: 500;
	display: flex;
	align-items: center;
	margin-bottom: 20upx;
	padding: 30upx 0;
}
.answer-choose-active {
	background: #ECF6F0;
	color: #219F64;
}
.answer-choose-left {
	flex: 1;
	padding-left: 30upx;
}
.answer-choose-right {
	padding-right: 60upx;
}
.answer-btn {
	width: 690upx;
	height: 100upx;
	line-height: 100upx;
	color: #fff;
	background-color: #00BF90;
	text-align: center;
	border-radius: 50upx;
}
/* 后期添加 */
.video-date{
	width: 100%;
	display: flex;
	margin-bottom: 40upx;
	align-items: center;
}
.video-date-end-date{
	font-size: 34upx;
	font-weight: 500;
	color: #999999;
}
.video-date-value{
	font-size: 34upx;
	color: #EA7C0F;
	font-weight: 500;
}
.video-desc{
	width: 100%;
	background-color: #E2E2E2;
	border-radius: 4upx;
	box-sizing: border-box;
	padding: 16upx;
	margin-bottom: 40upx;
}
.video-desc-item{
	width: 100%;
	display: flex;
	box-sizing: border-box;
	margin-bottom: 8upx;
	color: #666;
	font-size: 30upx;
	align-items: center;
}
.video-desc .icon{
	width: 30upx;
	height: 30upx;
	margin-right: 10upx;
	display: flex;
	align-items: center;
	justify-content: center;
}
</style>
